//
//  ViewController.m
//  接收端
//
//  Created by apple on 16/4/6.
//  Copyright © 2016年 SherrySorftware. All rights reserved.
//

#import "ViewController.h"
#import "BabyBluetooth.h"
@interface ViewController ()
{
    //BabyBluetooth *CVBaby;
}
@property (weak, nonatomic) IBOutlet UILabel *lab_state;
@property (weak, nonatomic) IBOutlet UILabel *lab_message;
@property (weak, nonatomic) CBPeripheral *tempPeripheral;
@property (weak, nonatomic) BabyBluetooth *CVBaby;
@end

@implementation ViewController
@synthesize CVBaby;



- (void)viewDidLoad {
    [super viewDidLoad];
    //单例初始化 推荐
    CVBaby = [BabyBluetooth shareBabyBluetooth];
    CVBaby.scanForPeripherals().connectToPeripherals().begin();
    
    //    NSUserDefaults *defs = [[NSUserDefaults alloc]init];
//    if ([defs valueForKey:@"identifier"]) {
//        NSString *str = [defs valueForKey:@"identifier"];
//        CBUUID *uuid = [CBUUID UUIDWithString:str];
//        NSMutableArray *arr = [[NSMutableArray alloc]init];
//        [arr addObject:uuid];
//        NSArray *list = [self findDidConnectDivice:arr];
//        NSLog(@"%@",list);
//        self.tempPeripheral = [list lastObject];
//        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(connetP) name:@"POWEREDON" object:nil];
//    }else{
//        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(findConnetP) name:@"POWEREDONSEARCH" object:nil];
//    }
    //[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(findConnetP) name:@"POWEREDONSEARCH" object:nil];


    __weak typeof(self) weakSelf = self;
    [CVBaby setBlockOnCentralManagerDidUpdateState:^(CBCentralManager *central) {
        if (central.state == CBCentralManagerStatePoweredOn) {
            [weakSelf.lab_state setText:@"设备打开成功，开始扫描设备"];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"POWEREDON" object:nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"POWEREDONSEARCH" object:nil];
        }
    }];
    
    //设置扫描到设备的委托
    [CVBaby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        NSLog(@"搜索到了设备:%@",peripheral.name);
        if([peripheral.name hasPrefix:@"myP"]) {
           // [central connectPeripheral:peripheral options:nil];
        }
    }];
    
    //设置查找设备的过滤器
         __block BOOL isFirst = YES;
    [CVBaby setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
        
        //最常用的场景是查找某一个前缀开头的设备
        if ([peripheralName hasPrefix:@"myP"] && isFirst == YES && peripheralName.length >6) {
            isFirst = NO;
            return YES;
        }
        return NO;
        
    }];
    
    //连接成功的回调
    [CVBaby setBlockOnConnected:^(CBCentralManager *central, CBPeripheral *peripheral) {
        //保存设备信息
        NSLog(@"连接成功，报存uuid");
        NSLog(@"%@",peripheral);
        NSUserDefaults *def = [[NSUserDefaults alloc]init];
        NSString *Pname = [peripheral name];
        [def setObject:Pname forKey:@"Pname"];
        [def setObject:[NSString stringWithFormat:@"%@",peripheral.identifier.UUIDString] forKey:@"identifier"];
        [weakSelf setReconnect:Pname];
        [CVBaby cancelScan];
    }];
    //设置发现设备的Services的委托
    [CVBaby setBlockOnDiscoverServices:^(CBPeripheral *peripheral, NSError *error) {
        for (CBService *service in peripheral.services) {
            NSLog(@"搜索到服务:%@",service.UUID.UUIDString);
        }
    }];
    //设置发现设service的Characteristics的委托
    [CVBaby setBlockOnDiscoverCharacteristics:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
        NSLog(@"===service name:%@",service.UUID);
        for (CBCharacteristic *c in service.characteristics) {
            NSLog(@"charateristic name is :%@",c.UUID);
        }
    }];
    //设置读取characteristics的委托
    [CVBaby setBlockOnReadValueForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        NSLog(@"characteristic name:%@ value is:%@",characteristics.UUID,characteristics.value);
        //订阅通知
        for (CBDescriptor *d in characteristics.descriptors) {
            NSLog(@"Descriptor uuid:%@",d.UUID);
            [peripheral setNotifyValue:YES forCharacteristic:characteristics];
        }
    }];
    
    //设置发现characteristics的descriptors的委托
    [CVBaby setBlockOnDiscoverDescriptorsForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristic, NSError *error) {
        NSLog(@"===characteristic name:%@",characteristic.service.UUID);
        for (CBDescriptor *d in characteristic.descriptors) {
            NSLog(@"CBDescriptor name is :%@",d.UUID);
        }
    }];
    //设置读取Descriptor的委托
    [CVBaby setBlockOnReadValueForDescriptors:^(CBPeripheral *peripheral, CBDescriptor *descriptor, NSError *error) {
        NSLog(@"Descriptor name:%@ value is:%@",descriptor.characteristic.UUID, descriptor.value);
    }];
    
    //读取值
    [CVBaby setBlockOnDiscoverDescriptorsForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristic, NSError *error) {
        NSString* aStr;
        aStr = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
        NSLog(@"%@",aStr);
        [weakSelf.lab_message setText:aStr];
    }];
    
    [CVBaby setBlockOnCancelAllPeripheralsConnectionBlock:^(CBCentralManager *centralManager) {
        NSLog(@"setBlockOnCancelAllPeripheralsConnectionBlock");
    }];
    
    [CVBaby setBlockOnCancelScanBlock:^(CBCentralManager *centralManager) {
        NSLog(@"setBlockOnCancelScanBlock");
    }];
    
    
    /*设置babyOptions
     
     参数分别使用在下面这几个地方，若不使用参数则传nil
     - [centralManager scanForPeripheralsWithServices:scanForPeripheralsWithServices options:scanForPeripheralsWithOptions];
     - [centralManager connectPeripheral:peripheral options:connectPeripheralWithOptions];
     - [peripheral discoverServices:discoverWithServices];
     - [peripheral discoverCharacteristics:discoverWithCharacteristics forService:service];
     
     该方法支持channel版本:
     [CVBaby setBabyOptionsAtChannel:<#(NSString *)#> scanForPeripheralsWithOptions:<#(NSDictionary *)#> connectPeripheralWithOptions:<#(NSDictionary *)#> scanForPeripheralsWithServices:<#(NSArray *)#> discoverWithServices:<#(NSArray *)#> discoverWithCharacteristics:<#(NSArray *)#>]
     */
    
    //示例:
    //扫描选项->CBCentralManagerScanOptionAllowDuplicatesKey:忽略同一个Peripheral端的多个发现事件被聚合成一个发现事件
    NSDictionary *scanForPeripheralsWithOptions = @{CBCentralManagerScanOptionAllowDuplicatesKey:@YES};
    //连接设备->
    [CVBaby setBabyOptionsWithScanForPeripheralsWithOptions:scanForPeripheralsWithOptions connectPeripheralWithOptions:nil scanForPeripheralsWithServices:nil discoverWithServices:nil discoverWithCharacteristics:nil];
    
}
///设置自动重连
- (void)setReconnect:(NSString*)Pname{
    [CVBaby AutoReconnect:[CVBaby findConnectedPeripheral:Pname]];
}
///查找已经连接过的设备
- (NSArray*)findDidConnectDivice:(nonnull NSArray *)cbuuidArr {
    //retrieveConnectedPeripheralsWithServices:
    //return [manager retrieveConnectedPeripheralsWithServices:cbuuidArr];
    return [[CVBaby centralManager] retrievePeripheralsWithIdentifiers:cbuuidArr];
}

- (void)connetP {
    CVBaby.having(self.tempPeripheral).connectToPeripherals().begin();
    [CVBaby AutoReconnect:self.tempPeripheral];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"POWEREDON" object:nil];
}

- (void)findConnetP {
    CVBaby.scanForPeripherals().connectToPeripherals().begin();
//    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"POWEREDONSEARCH" object:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
